

import 'package:wu_you/data/db/db.dart';

class SearchHistoryDao {
  factory SearchHistoryDao() => _getInstance();
  static SearchHistoryDao _instance;

  SearchHistoryDao._internal();

  static SearchHistoryDao _getInstance() {
    if (_instance == null) {
      _instance = SearchHistoryDao._internal();
    }
    return _instance;
  }

  static const _TABLE_NAME = "search_history";

  ///查询所有
  Future<List<String>> getAll(String mobile) async {
    var db = await DatabaseHelper().db();
    List<Map<String, Object>> result = await db.query(
      _TABLE_NAME,
      columns: ["search_content"],
      where: 'mobile = ?',
      whereArgs: [mobile],
      orderBy: 'search_count desc',
    );
    return result.map((e) => e['search_content'] as String).toList();
  }

  ///插入新数据
  ///如果存在则更新搜索次数
  Future<int> insert(String mobile, String searchContent) async {
    var db = await DatabaseHelper().db();
    int result = 0;
    int count = await db.rawUpdate("update search_history set search_count = search_count + 1 where mobile = ? and search_content = ?", [mobile, searchContent]);
    result = count;
    if (count == 0) {
      int res = await db.insert(_TABLE_NAME, {"mobile": mobile, "search_content": searchContent, "search_count": 1});
      result = res;
    }
    return result;
  }

  ///删除
  Future<int> delete(String mobile, String content) async {
    var db = await DatabaseHelper().db();
    int result = 0;
    result = await db.delete(_TABLE_NAME, where: 'search_content = ? and mobile = ?', whereArgs: [content, mobile]);
    return result;
  }

  ///删除所有
  Future<int> deleteAll(String mobile) async {
    var db = await DatabaseHelper().db();
    int result = 0;
    result = await db.delete(_TABLE_NAME, where: 'mobile = ?', whereArgs: [mobile]);
    return result;
  }
}
